package com.jiyici.network;

import jiyici.Constant.ResponseSpec;

import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

import com.jiyici.R;
import com.jiyici.utils.StringUtils;

public class Result {

    private static Result REQUEST_ERROR_RESULT = new Result() {

        public boolean isSuccess() {
            return false;
        }

        public CharSequence getErrorMsg(Context context) {
            return context.getText(R.string.error_request);
        }
    };

    public static Result parseResponse(final String response) {
        if (StringUtils.isBlank(response))
            return REQUEST_ERROR_RESULT;
        try {
            JSONObject json = new JSONObject(response);
            Result result = new Result();
            result.action = json.getInt(ResponseSpec.KEY_ACTION);
            result.result = json.getInt(ResponseSpec.KEY_RESULT);
            if (result.isSuccess()) {
                result.data = json.getJSONObject(ResponseSpec.KEY_DATA);
            } else {
                result.errorCode = json.getInt(ResponseSpec.KEY_ERROR);
            }
            return result;
        } catch (Exception e) {
            Log.e("", "parse json response error", e);
            return REQUEST_ERROR_RESULT;
        }
    }

    public int getAction() {
        return action;
    }

    public boolean isSuccess() {
        return result == ResponseSpec.SUCCESS;
    }

    public CharSequence getErrorMsg(Context context) {
        int errorResourceId = Errors.getErrorString(errorCode);
        return context.getText(errorResourceId);
    }

    public JSONObject getData() {
        return data;
    }

    private int action;

    private int result;

    private int errorCode;

    private JSONObject data;

}
